<template>
    <div class="e-form">
        <BillTop title="配置计划编辑" @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <!-- 基本信息 -->
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="计划明细" name="planDetail" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="变更历史" name="changeHistory" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <div style="width: 100%" class="form">
                                <el-form ref="form" :model="formData.planConfiguration" :rules="rules" label-width="200px">
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="计划编号：" >
                                                <span>{{ formData.planConfiguration.billNo}}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="计划日期：" prop="billDate">
                                                <el-date-picker
                                                    v-model="formData.planConfiguration.billDate"
                                                    type="date"
                                                    placeholder="选择日期"
                                                    value-format="yyyy-MM-dd"
                                                    :clearable="false"
                                                >
                                                </el-date-picker>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="填报人：" prop="founderName">
                                                <span>{{ formData.planConfiguration.founderName }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="币种：" prop="currencyId">
                                                <el-select
                                                    v-model="formData.planConfiguration.currencyId"
                                                    placeholder="请选择"
                                                    @change="currencyChange"
                                                >
                                                    <el-option
                                                        v-for="(
                                                            item
                                                        ) in currencyForm"
                                                        :key="item.value"
                                                        :label="item.label"
                                                        :value="item.value"
                                                    >
                                                    </el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="总计划金额（元）：" prop="planAmount">
                                                <span>{{ formData.planConfiguration.planAmount }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="长租计划金额（元）：" prop="longPlanAmount">
                                                <span>{{ formData.planConfiguration.longPlanAmount }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="临租总金额（元）：" prop="tempLeaseAmount">
                                                <el-input
                                                    placeholder="请输入内容"
                                                    v-model="formData.planConfiguration.tempLeaseAmount"
                                                    @blur="onPlanAmount"
                                                    v-enter-float="{
                                                        set: formData,
                                                        val: 'planConfiguration',
                                                        key: 'tempLeaseAmount'
                                                    }"
                                                    clearable>
                                                </el-input>
                                            </el-form-item>
                                        </el-col>
                                    <el-col :span="12">
                                            <el-form-item label="临租审核总金额（元）：">
                                                <el-input
                                                    placeholder="请输入内容"
                                                    v-model="formData.planConfiguration.tempLeaseAuditAmount"
                                                    v-enter-float="{
                                                        set: formData,
                                                        val: 'planConfiguration',
                                                        key: 'tempLeaseAuditAmount'
                                                    }"
                                                    :disabled="statusLable(formData.planConfiguration.state) !== '审核中'"
                                                    clearable>
                                                </el-input>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="机构："  prop="orgName">
                                                    <span>{{ formData.planConfiguration.orgName }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="状态：" prop="state">
                                                <span>{{ statusLable(formData.planConfiguration.state) }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-form-item  label="备注：">
                                            <el-input type="textarea" v-model="formData.planConfiguration.remarks" maxlength="500"></el-input>
                                        </el-form-item>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="本位币：" prop="baseCurName">
                                                <span>{{ formData.planConfiguration.baseCurName }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="人民币汇率：" prop="rmbRate">
                                                <span>{{formData.planConfiguration.rmbRate}}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row v-if="showBaseCurName">
                                        <el-col :span="12">
                                            <el-form-item label="本位币汇率：" prop="baseCurRate">
                                                <el-input
                                                    v-model="formData.planConfiguration.baseCurRate"
                                                    @blur="onScSumCost"
                                                    v-enter-float2="{
                                                        set: formData,
                                                        val: 'planConfiguration',
                                                        key: 'baseCurRate'
                                                    }"
                                                    placeholder="请输入内容"
                                                    :disabled="!showBaseCurName"
                                                    clearable>
                                                </el-input>
                                            </el-form-item>
                                        </el-col>
                                        <!-- <el-col :span="12">
                                            <el-form-item label="计划金额（本位币）：">
                                                <span>{{ formData.planConfiguration.baseCurPlanAmount }}</span>
                                            </el-form-item>
                                        </el-col> -->
                                    </el-row>
                                </el-form>
                            </div>
                        </div>
                    </div>

                    <div id="planDetailCon" class="con">
                        <div class="tabs-title" id="planDetail">计划明细</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <div>
                                        <el-button class="btn-greenYellow" @click="selectEquip">选择基础库设备</el-button>
                                        <el-button class="btn-delete"  @click="deletePlanList " v-if="isBatch[0].flag">批量删除</el-button>
                                    </div>
                                    <div class="batchBox" @click="batchOperation('planDetail')">
                                        <img class="batchicon" src="@/assets/piliang.png">
                                        <span class="batchfont">{{isBatch[0].batch}}</span>
                                    </div>
                                </div>
                            </div>
                            <div class="errorMsg" v-if="errorMsg.length>0">
                                <span v-for="item,index in errorMsg" :key="index">
                                    {{item}}
                                </span>
                            </div>
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="planTable"
                                :data="planConfigurationDtlListCopy"
                                border
                                style="width: 100%"
                                @selection-change="planTableSelect"
                                :row-class-name="tableRowClass"
                                v-sortTable="{ 'tableData': planConfigurationDtlListCopy, '_this': this, 'ref': 'planTable' }"
                            >
                                <el-table-column  fixed type="selection" width="55" align="center" v-if="isBatch[0].flag">
                                </el-table-column>
                                <el-table-column  fixed type="index" label="序号" width="80" align="center">
                                </el-table-column>
                                 <el-table-column fixed label="操作" width="70">
                                    <template slot-scope="{ row,$index }">
                                        <div class="handle">
                                            <div style=" cursor: pointer;">
                                                <img src="@/assets/btn/delete.png"  @click="handleDelete(row,$index)">
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="equipmentName" label="设备名称" width="200" align="center">
                                </el-table-column>
                                <el-table-column
                                    prop="categoryName"
                                    label="设备类别"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="specificationModel"
                                    label="规格型号"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.specificationModel" clearable @input="curStateChange(row)"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="计量单位"
                                    width="120"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="quantity"
                                    label="需求数量"
                                    width="150"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model.number="row.quantity" clearable @input="curStateChange(row)"
                                        v-enter-integer1="{
                                            set: row,
                                            key: 'quantity'
                                        }"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="allocateQuantity"
                                    label="可调配数"
                                    width="150"
                                    align="center"
                                    v-if="formData.planConfiguration.state>0"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model.number="row.allocateQuantity" clearable @input="curStateChange(row)"
                                        v-enter-integer1="{
                                            set: row,
                                            key: 'allocateQuantity'
                                        }"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="purchaseQuantity"
                                    label="建议采购数"
                                    width="150"
                                    align="center"
                                     v-if="formData.planConfiguration.state>0"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model.number="row.purchaseQuantity" clearable @input="curStateChange(row)"
                                        v-enter-integer1="{
                                            set: row,
                                            key: 'purchaseQuantity'
                                        }"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="tenancyQuantity"
                                    label="建议租赁数"
                                    width="150"
                                    align="center"
                                    v-if="formData.planConfiguration.state>0"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input  v-model="row.tenancyQuantity" clearable @input="curStateChange(row)"
                                        v-enter-integer1="{
                                            set: row,
                                            key: 'tenancyQuantity'
                                        }"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="serviceTime"
                                    label="预计使用时间"
                                    width="150"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.serviceTime" clearable @input="curStateChange(row)"
                                        v-enter-float="{
                                            set: row,
                                            key: 'serviceTime'
                                        }"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="price"
                                    label="单价（元）"
                                    width="150"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.price" clearable @input="curStateChange(row)"
                                        v-enter-float="{
                                            set: row,
                                            key: 'price'
                                        }"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="amount"
                                    label="金额（元）"
                                    width="130"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{row.amount}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="enterDate"
                                    label="预计进场时间"
                                    width="150"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-date-picker type="date" placeholder="选择日期" v-model="row.enterDate" style="width: 100%;" value-format="yyyy-MM-dd"
                                            @input="curStateChange(row)"></el-date-picker>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="exitDate"
                                    label="预计退场时间"
                                    width="150"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-date-picker type="date" placeholder="选择日期" v-model="row.exitDate" style="width: 100%;" value-format="yyyy-MM-dd"
                                            @input="curStateChange(row)"></el-date-picker>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="timeUnit"
                                    label="计时单位"
                                    width="150"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-select
                                            v-model="row.timeUnit"
                                            placeholder="请选择"
                                            @input="curStateChange(row)"
                                        >
                                            <el-option
                                                v-for="(
                                                    item
                                                ) in timeUnitList"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.label"
                                            >
                                            </el-option>
                                        </el-select>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="useage"
                                    label="用途"
                                    min-width="200"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-model="row.useage" clearable @input="curStateChange(row)"></el-input>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp :relationId="attachId" bucketName="facilityplan" />
                    </div>

                    <div id="changeHistoryCon" class="con">
                        <div class="tabs-title" id="changeHistory">变更历史</div>
                        <div class="e-table">
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="changeHistorySelect"
                                :data="changeHistoryTable"
                                border
                            >
                                <el-table-column type="selection" align="center" width="55" v-if="isBatch[1].flag">
                                </el-table-column>
                                <el-table-column fixed label="操作" width="70">
                                    <template slot-scope="{row}">
                                        <div class="handle">
                                            <div style=" cursor: pointer;">
                                                <img src="@/assets/btn/delete.png"  @click="handleDeleteHistory(row,$index)">
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="changeBillNo"  align="center" label="变更编号" show-overflow-tooltip min-width="200" class-name="blue-column">
                                        <template slot-scope="{ row }" >
                                            <span @click="tableDbShow(row)">{{row.changeBillNo}}</span>
                                        </template>
                                </el-table-column>
                                <el-table-column
                                    prop="billDate"
                                    label="变更日期"
                                    align="center"
                                    width="150"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="orgName"
                                    label="机构"
                                    align="left"
                                    show-overflow-tooltip min-width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="planAmount"
                                    label="变更前金额"
                                    align="center"
                                    width="150"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="changePlanAmount"
                                    label="变更后金额"
                                    align="center"
                                    width="150"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="number"
                                    label="变更期数"
                                    width="150"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="state"
                                    label="状态"
                                    width="120"
                                    align="center"
                                >
                                <template slot-scope="{row}">
                                    <span>{{statusLable(row.state)}}</span>
                                </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                billType="5011"
                                :tableData.sync="auditHistoryTable"
                                @getAuditHistory="getAuditHistory"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{height: seatHeight + 'px'}"></div>
        <div class="buttons">
            <ComExaButtons :auditState="auditState" :state="formData.planConfiguration.state" @exas="exas" :founderId="formData.planConfiguration.founderId" />
            <el-button size="small" @click="handleClose">取消</el-button>
        </div>
    </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import $ from 'jquery'
import request from '@/api/equip/equipPlan.js'
import requestAudit from '@/api/equip/common.js'
import count from '@/api/equip/equipPlanCount.js'
import '@/utils/jquery.scrollTo.min'
import AttachComp from '@/components/common/attachIndex'
import ComAuditHistoryIndex from '@/pages/equipment/components/auditHistory/auditHistoryIndex'
import { hideLoading } from '@/utils/common'
import { selectEquipmentBase } from '@/api/equip/popupCallback.js'
import { exas, saveAll, submitCommit } from '@/pages/equipment/components/auditHistory/equipCom.js'
export default {
    data () {
        return {
            billid: this.$route.query.billid,
            isBatch: [
                {
                    flag: true,
                    batch: '进入批量管理'
                },
                {
                    flag: true,
                    batch: '进入批量管理'
                }
            ],
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            selectEquipVisible: false,
            formData: {
                planConfiguration: {
                    'auditTime': '',
                    'auditor': '',
                    'auditorId': '',
                    'baseCurId': '',
                    'baseCurName': '',
                    'baseCurPlanAmount': null,
                    'baseCurRate': null,
                    'billDate': '',
                    'billId': '',
                    'billNo': '',
                    'changeBillId': '',
                    'changeBillNo': '',
                    'changeLongPlanAmount': null,
                    'changePlanAmount': null,
                    'changeState': '',
                    'changeTempLeaseAmount': null,
                    'changeTempLeaseAuditAmount': null,
                    'currency': '',
                    'currencyId': '',
                    'founderId': '',
                    'founderName': '',
                    'longPlanAmount': null,
                    'modifier': '',
                    'modifierId': '',
                    'nullifyCreated': '',
                    'nullifyCreator': '',
                    'nullifyCreatorId': '',
                    'nullifyDesciption': '',
                    'nullifyReason': '',
                    'number': 0,
                    'orgId': '',
                    'orgName': '',
                    'planAmount': null,
                    'recorder': '',
                    'recorderId': '',
                    'remarks': '',
                    'rmbId': '',
                    'rmbName': '',
                    'rmbRate': null,
                    'rmbSumTempLeaseAmount': null,
                    'state': '',
                    'tempLeaseAmount': null,
                    'tempLeaseAuditAmount': null,
                    'version': null,
                    'workId': ''
                }
            },
            planConfigurationDtlList: [], //计划明细
            planConfigurationDtlListCopy: [],
            planSelect: [], //计划明细选择项
            changeHistoryTable: [], //变更历史
            changeHistorySelect: [], //变更历史选择项
            auditHistoryTable: [],
            rules: {
                billDate: [
                    { required: true, message: '请选择日期', trigger: 'blur' },
                ],
                currencyId: [
                    { required: true, message: '请选择币种', trigger: 'change'  },
                ],
                baseCurName: [
                    { required: true, message: '请输入本位币', trigger: 'blur' },
                ],
                baseCurRate: [
                    { required: true, message: '请输入本位币汇率', trigger: 'change' }
                ],
            },
            auditState: {}, //流程按钮显示状态
            auditParams: {
                'billId': this.$route.query.billid,
                'billType': 5011,  //配置计划
                'freeNextUnitIndex': 0,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': '',
                'orgId': '',
                'orgName': '',
                'userId': '',
                'workId': ''
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 5011,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },
            currentRow: {}, //计划明细当前行数据
            showBaseCurName: false,
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [], //计划明细错误显示
            isErrorMsg: true, //是否提醒错误信息
            request: {}
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            timeUnitList: state => state.equip.equipData.timeUnitList //计时单位
        }),
        statusLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.state
                const obj = state.find(x=>+x.value === param)
                if(obj !== undefined) {
                    return obj.label
                }
            }
        },
        attachId () {
            return this.$route.query.billid
        },
        //当前单据状态
        state () {
            return this.formData.planConfiguration.state
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        }
    },
    components: {
        AttachComp,
        //ComExaButtons,
        ComAuditHistoryIndex
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    created () {
        this.userId = localStorage.getItem('userId')
        this.getDicValue()
    },
    mounted () {
        this.init()  //初始化所有数据
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'planDetail', 'attach', 'changeHistory', 'auditHistory']
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()
    },
    methods: {
        ...mapMutations(['setSelectedInfo', 'setAuditParams']),
        //获取当前使用的字典
        getDicValue () {
            this.$store.dispatch('equip/setTimeUnitList')
        },
        batchOperation (name) {
            switch(name) {
            case 'planDetail':
                this.isBatch[0].flag = !this.isBatch[0].flag
                if(this.isBatch[0].flag) {
                    this.isBatch[0].batch = '退出批量管理'
                    this.$refs.planTable.clearSelection()
                }else{
                    this.isBatch[0].batch = '进入批量管理'
                }
                break
            case 'changeHistory':
                this.isBatch[1].flag = !this.isBatch[1].flag
                if(this.isBatch[1].flag) {
                    this.isBatch[1].batch = '退出批量管理'
                    this.$refs.changeHistorySelect.clearSelection()
                }else{
                    this.isBatch[1].batch = '进入批量管理'
                }
                break
            }

        },
        //跳转到明细
        scorllDtl () {
            if(this.$route.query.name) {
                setTimeout(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        //去变更新增页面
        handleChange () {
            const billid = this.billid
            this.$router.push({
                path: '/configPlanListChangeAdd',
                query: { billid }
            })
        },
        //去变更编辑页面
        tableEdit (billid) {
            this.$router.push({
                path: '/configPlanListChangeEdit',
                query: { billid }
            })
        },
        //变更查看页面
        tableDbShow (row) {
            if(row.state === -1 || row.state === 2 || row.state === 5) {
                this.$router.push({
                    path: '/configPlanListChangeShow',
                    query: { billid: row.billId }
                })
            }else{
                this.auditParams.billId = row.billId
                requestAudit.getCurrentUnitInfo(this.auditParams).then(res => {
                    this.auditState = res
                    if( this.auditState.canModify == true) {
                        this.$router.push({
                            path: '/configPlanListChangeEdit',
                            query: { billid: row.billId }
                        })
                    }else{
                        this.$router.push({
                            path: '/configPlanListChangeShow',
                            query: { billid: row.billId }
                        })
                    }
                })
            }
        },
        //初始化数据
        init () {
            Promise.all([
                this.getInfo(),
                this.getPlanList(),
                this.getChangeHistory(),
                this.getAuditHistory(),
                this.getCurrentUnitInfo()  //获取流程按钮显示状态
            ]).finally(() => {
                hideLoading()
            })
        },
        //刷新历史审核列表
        getAuditHistory () {
            requestAudit.history(this.auditParams).then(res=>{
                this.auditHistoryTable = res
            })
        },
        //如果是-1就隐藏
        tableRowClass ({ row }) {
            if(row.changeType === -1) {
                return  'row-hide'
            }else{
                return  'row-show'
            }
        },
        //选择设备基础库
        selectEquip () {
            let json = {
                'categoryId': '00000',
                'isUpdate': false,
                'keyword': ''
            }
            selectEquipmentBase(json).then(res=>{
                res.forEach(item=>{
                    let obj = {
                        'allocateQuantity': null,
                        'amount': null,
                        'billId': this.billid,
                        'billNo': '',
                        'categoryId': '',
                        'categoryName': '',
                        'changeType': 1,
                        'configurationPlanDtlId': '',
                        'enterDate': '',
                        'equipmentId': '',
                        'equipmentName': '',
                        'exitDate': '',
                        'oldState': '',
                        'oneLevelCategoryId': '',
                        'oneLevelCategoryName': '',
                        'price': null,
                        'purchaseQuantity': null,
                        'quantity': null,
                        'serviceTime': null,
                        'specificationModel': '',
                        'state': '',
                        'tenancyQuantity': null,
                        'timeUnit': '',
                        'unit': '',
                        'useage': '',
                        ...item
                    }
                    obj.state = null
                    this.planConfigurationDtlListCopy.push(obj)
                    this.planConfigurationDtlList.push(obj)
                })
            })
        },
        //计算金额 = 需求数量*预计使用时间*单价
        onAmount  (row) {
            row.amount = count.onAmount(row.quantity, row.serviceTime, row.price)
            this.onUpCollect()
        },
        //长租计划金额 = 明细获取金额向上汇总
        onUpCollect () {
            this.formData.planConfiguration.longPlanAmount = null
            this.formData.planConfiguration.longPlanAmount = count.onUpCollect(this.planConfigurationDtlList)
            this.onPlanAmount()
        },
        //总计划金额 = 金额的汇总数据+临租总金额
        onPlanAmount () {
            this.formData.planConfiguration.planAmount = count.onPlanAmount(this.planConfigurationDtlList, this.formData.planConfiguration.tempLeaseAmount)
            this.formData.planConfiguration.tempLeaseAuditAmount = this.formData.planConfiguration.tempLeaseAmount
            // if(this.formData.planConfiguration.state === 0) {
            //     this.formData.planConfiguration.tempLeaseAuditAmount = this.formData.planConfiguration.tempLeaseAmount
            // }
            this.onScSumCost()
        },
        //计划金额（本位币）=总计划金额+本位币汇率
        onScSumCost () {
            this.formData.planConfiguration.baseCurPlanAmount = count.onScSumCost(this.formData.planConfiguration.planAmount, this.formData.planConfiguration.baseCurRate)
        },
        //判断当前状态是否已修改
        curStateChange (row) {
            this.currentRow = row
            if (row.configurationPlanDtlId) {
                this.currentRow.changeType = 2
            }
            this.onAmount(row)
        },
        //单个删除计划明细
        handleDelete (row, $index) {
            let length = this.errorMsg.length
            this.clientPop(
                'info',
                this.oneDeleteErr,
                ()=>{
                    if(row.configurationPlanDtlId) {
                        this.$set(this.planConfigurationDtlList[$index], 'changeType', -1)
                        this.planConfigurationDtlListCopy.splice($index, 1)
                        this.onUpCollect()
                        if (length > 0 ) {
                            this.verifyTable()
                        }
                    }else{
                        this.planConfigurationDtlList.splice($index, 1)
                        this.planConfigurationDtlListCopy.splice($index, 1)
                        this.onUpCollect()
                        if (length > 0 ) {
                            this.verifyTable()
                        }
                    }
                }
            )
        },
        //获取计划明细表格的选择项
        planTableSelect (selection) {
            this.planSelect = selection
        },
        //点击删除弹窗
        deletePlanList () {
            const length = this.planSelect.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择数据,请选择!',
                )
            }else{
                this.clientPop(
                    'info',
                    this.moreDeleteErr(length),
                    this.delete
                )
            }

        },
        //批量删除计划明细
        delete () {
            let length = this.errorMsg.length
            if (this.planSelect.length > 0) {
                this.planSelect.forEach(item=>{
                    if(item.configurationPlanDtlId) {
                        this.$set(item, 'changeType', -1)
                        for(let i = this.planConfigurationDtlListCopy.length; i > 0; i--) {
                            if(this.planConfigurationDtlListCopy[i - 1] === item) {
                                this.planConfigurationDtlListCopy.splice(i - 1, 1)
                            }
                        }
                        this.onUpCollect()
                        if (length > 0 ) {
                            this.verifyTable()
                        }
                        this.$refs.planTable.clearSelection()
                    }else{
                        const localArr = []
                        localArr.push(item)
                        for(let i = this.planConfigurationDtlList.length; i > 0; i--) {
                            for(let j = 0; j < localArr.length; j++) {
                                if(this.planConfigurationDtlList[i - 1] === localArr[j]) {
                                    this.planConfigurationDtlList.splice(i - 1, 1)
                                    this.onUpCollect()
                                    if (length > 0 ) {
                                        this.verifyTable()
                                    }
                                }
                                if(this.planConfigurationDtlListCopy[i - 1] === localArr[j]) {
                                    this.planConfigurationDtlListCopy.splice(i - 1, 1)
                                    this.onUpCollect()
                                    if (length > 0 ) {
                                        this.verifyTable()
                                    }
                                }
                            }
                        }
                        this.$refs.planTable.clearSelection()
                    }
                })
            }
        },
        /* 获取数据 */
        //币种切换
        currencyChange (val) {
            this.formData.planConfiguration.currency = this.currencyForm.find(x=>x.value === val).label  //币种
            requestAudit.getRmbRate({  //获取机构下某币种的人民币汇率
                currency: val,
                orgId: this.userInfo.orgInfo.orgId
            }).then(res=>{
                if(res.rate === 1) {
                    this.formData.planConfiguration.rmbId = res.currency
                    this.formData.planConfiguration.rmbRate = res.rate
                }else{
                    this.formData.planConfiguration.rmbId = res.rateId
                    this.formData.planConfiguration.rmbRate = res.rate
                }
            }).catch(()=>{

            })
            if(this.formData.planConfiguration.currencyId === this.formData.planConfiguration.baseCurId) {   //币种=本位币
                this.formData.planConfiguration.baseCurRate = 1
                this.showBaseCurName = false
            }else{
                this.formData.planConfiguration.baseCurRate = null
                this.formData.planConfiguration.baseCurPlanAmount = null
                this.showBaseCurName = true
            }
        },
        //基本信息查询
        getInfo () {
            const params = {
                planId: this.billid,
                userId: this.userId
            }
            request.getConfigBaseInfo(params).then(res=>{
                this.formData.planConfiguration = res.planConfiguration
                this.onScSumCost()
                if(this.formData.planConfiguration.currencyId !== this.formData.planConfiguration.baseCurId) {
                    this.showBaseCurName = true
                }
            })
        },
        //计划明细查询
        getPlanList () {
            const params = {
                planId: this.billid,
                userId: this.userId
            }
            request.getconfigurationInfo(params).then(res=>{
                this.planConfigurationDtlListCopy = []
                this.planConfigurationDtlList = res.planConfigurationDtlList
                res.planConfigurationDtlList.map(item=>{
                    this.planConfigurationDtlListCopy.push(item)
                })
                //this.onUpCollect()
            })
        },
        //变更历史查询
        getChangeHistory () {
            const params = {
                planId: this.billid,
                userId: this.userId
            }
            request.getConfigChangeHistory(params).then(res=>{
                this.changeHistoryTable = res.planConfigurationList
            })
        },
        getNowDate () {
            this.$set(
                this.formData,
                'applyTime',
                new Date()
                    .toLocaleDateString()
                    .replace(new RegExp('/', 'g'), '-')
            )
        },
        //获取流程按钮显示状态
        getCurrentUnitInfo () {
            requestAudit.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject)=>{
                request.updateConfigBaseInfo(this.formData).then(()=>{
                    this.verifyTable().then(()=>{
                        request.updateDetailInfo(this.planConfigurationDtlList).then(()=>{
                            resolve()
                        }).catch(err=>{
                            this.setError('planDetail')
                            reject(err)
                            this.scorllError()
                        })
                    }).catch(err=>{
                        this.setError('planDetail')
                        reject(err)
                        this.scorllError()
                    })

                }).catch(err=>{
                    this.setError('baseInfo')
                    reject(err)
                    this.scorllError()
                })
            })
        },
        //关闭
        handleClose () {
            this.$router.replace('/configPlanList')
        },
        //计划明细非空验证
        verifyTable () {
            return  new Promise((resolve, reject)=>{
                this.errorMsg = []
                this.planConfigurationDtlListCopy.forEach((item, index)=>{
                    if(item.changeType !== -1) {
                        if( item.specificationModel === '' || item.specificationModel === null) {
                            let str = `请填写第 ${index + 1} 行的（规格型号）`
                            this.errorMsg.push(str)
                        }
                        if(item.serviceTime === null || item.serviceTime === '') {
                            let str = `请填写第 ${index + 1} 行的（预计使用时间）`
                            this.errorMsg.push(str)
                        }
                        if(item.price === null || item.price === '') {
                            let str = `请填写第 ${index + 1} 行的（单价）`
                            this.errorMsg.push(str)
                        }
                        if(item.enterDate === '' || item.enterDate === null) {
                            let str = `请选择第 ${index + 1} 行的（预计进场时间）`
                            this.errorMsg.push(str)
                        }else{
                            if(item.exitDate !== '') {
                                const enterDate = new Date(item.enterDate).getTime() //预计进场时间
                                const exitDate = new Date(item.exitDate).getTime() //预计退场时间
                                if(enterDate > exitDate) {
                                    let str = `第 ${index + 1} 行的（预计退场时间不能小于预计进场时间）`
                                    this.errorMsg.push(str)
                                }
                            }

                        }
                        if(item.timeUnit === null || item.timeUnit === '') {
                            let str = `请选择第 ${index + 1} 行的（计时单位）`
                            this.errorMsg.push(str)
                        }
                        if(this.formData.planConfiguration.state > 0) {
                            if(item.allocateQuantity === null || item.allocateQuantity === '') {
                                let str = `请填写第 ${index + 1} 行的（可调配数）`
                                this.errorMsg.push(str)
                            }
                            if(item.purchaseQuantity === null || item.purchaseQuantity === '') {
                                let str = `请填写第 ${index + 1} 行的（建议采购数）`
                                this.errorMsg.push(str)
                            }
                            if(item.tenancyQuantity === null || item.tenancyQuantity === '') {
                                let str = `请填写第 ${index + 1} 行的 (建议租赁数) `
                                this.errorMsg.push(str)
                            }
                            if((item.allocateQuantity !== null || item.allocateQuantity !== '') && (item.purchaseQuantity !== null || item.purchaseQuantity !== '') && (item.tenancyQuantity !== null || item.tenancyQuantity !== '')) {
                                if((item.allocateQuantity + item.purchaseQuantity + item.tenancyQuantity) > item.quantity || (item.allocateQuantity + item.purchaseQuantity + item.tenancyQuantity) === 0) {
                                    let str = `第 ${index + 1} 行的 “可调配数、建议采购数、建议租赁数之和必须大于0且不超过需求数量!”`
                                    this.errorMsg.push(str)
                                }
                            }

                        }
                    }

                })
                if(this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()
                }else{
                    this.isErrorMsg = false
                    resolve()
                }

            })

        },
        //保存全部数据
        saveAll () {
            this.errorList = []
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo()
                ]
            }
            saveAll(this, requestFn)
        },
        //保存并提交
        submitCommit () {
            if(this.formData.planConfiguration.tempLeaseAmount > this.formData.planConfiguration.longPlanAmount) {
                this.formData.planConfiguration.tempLeaseAmount = null
                this.clientPop('err', '临租总金额（元）不能大于长租计划金额（元）')
                this.setError('baseInfo')
                this.scorllError()
                return
            }
            if(this.planConfigurationDtlListCopy.length === 0) {
                let str = '计划明细不能空！'
                this.errorMsg.push(str)
                this.setError('planDetail')
                this.scorllError()
                return
            }
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo()
                ]
            }
            submitCommit(this, requestFn, 0)
        },
        //删除单据
        deleteBills () {
            let billids = [this.billid]
            this.clientPop(
                'info',
                this.oneDeleteErr,
                ()=>{
                    request.configPlanDelete(billids).then(()=>{
                        this.clientPop('suc', '删除成功', this.handleClose)
                    })
                }
            )
        },
        // 审核相关操作
        async exas (arg) {
            const requestFn = ()=>{
                return []
            }
            exas(arg, this, requestFn, 0)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}
.e-table {
    background: #fff;
}
</style>
